package com.teapos.service;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.teapos.dao.CustomerDao;
import com.teapos.dao.OrderDao;
import com.teapos.dao.PadDao;
import com.teapos.dao.UserDao;
import com.teapos.enumtype.PadOrderStatusEnum;
import com.teapos.enumtype.TeaTypeEnum;
import com.teapos.enumtype.TeaUnitEnum;
import com.teapos.enumtype.TradeTypeEnum;
import com.teapos.util.BusinessTool;
import com.teapos.util.Maps;
import com.teapos.util.PropUtil;
import com.teapos.util.Tool;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service
public class PadService {
	
	@Autowired
	private PadDao padDao;
	@Autowired
	private CustomerDao customerDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private OrderDao orderDao;
	
	public List getPadOrders(Map map) {
		List pads = padDao.findPadOrdersByPage(map);
		Iterator iter = pads.iterator();
		while(iter.hasNext()) {
			Map pad = (Map) iter.next();
			pad.put("area_sub_display", Tool.toBigDecimal(pad.get("area_sub")).divide(new BigDecimal("100")));
			pad.put("total_sub_display", Tool.toBigDecimal(pad.get("total_sub")).divide(new BigDecimal("100")));
			pad.put("status_display", PadOrderStatusEnum.getEnumByCode(Tool.toInt(pad.get("status"))).getDesc());
		}
		return pads;
	}
	
	public int getPadOrderCount(Map map) {
		return padDao.findPadOrderCount(map);
	}
	
	public Map getPadOrderDetail(int orderId) {
		Map order = padDao.findPadOrderById(orderId);
		order.put("area_sub_display", Tool.toBigDecimal(order.get("area_sub")).divide(new BigDecimal("100")));
		order.put("total_sub_display", Tool.toBigDecimal(order.get("total_sub")).divide(new BigDecimal("100")));
		//System.err.println(order);
		int hallId = Tool.toInt(order.get("hall_id"));
		int roomId = Tool.toInt(order.get("room_id"));
		Map hall = null;Map room = null;
		
		String ctype = Tool.toString(order.get("c_type"));
		int feetype = Tool.toInt(order.get("fee_type"));
		if(hallId!=0) {
			hall = padDao.findHallById(hallId);
			String ruleStr = Tool.toString(hall.get("rule"));
			Map rule = JSON.parseObject(ruleStr);
			Map ruleMap = (Map)rule.get(ctype);
			/*int start1 = Tool.toInt(hall.get("day_from"));
			int end1 = Tool.toInt(hall.get("day_end"));
			int start2 = Tool.toInt(hall.get("night_from"));
			int end2 = Tool.toInt(hall.get("night_end"));
			double dayPrice = Tool.toDouble(hall.get("day_price"));
			double nightPrice = Tool.toDouble(hall.get("night_price"));*/
			StringBuilder sb = new StringBuilder();
			sb.append("白天：").append(ruleMap.get("day_from")).append(":00到").append(ruleMap.get("day_end")).append(":00&nbsp;&nbsp;")
				.append("白天价格：").append(ruleMap.get("day_price")).append("元<br>")
				.append("晚上：").append(ruleMap.get("night_from")).append(":00到").append(ruleMap.get("night_end")).append(":00&nbsp;&nbsp;")
				.append("晚上价格：").append(ruleMap.get("night_price")).append("元<br>");
			hall.put("rule_display", sb.toString());
		}
		if(roomId!=0) {
			room = padDao.findRoomById(roomId);
			String ruleStr = Tool.toString(room.get("rule"));
			System.err.println(ruleStr);
			String desc = "";
			if(StringUtils.isNotBlank(ruleStr)) {
				Map rule = JSON.parseObject(ruleStr);
				Map ruleMap = (Map) rule.get(ctype);
				if(feetype==1) 
					desc = "价格：时间段计费"+ruleMap.get("hours")+"小时"+ruleMap.get("price")+"元";
				else if(feetype==2)
					desc = "价格：每小时计费"+ruleMap.get("per_price")+"元";
				/*List rules = JSON.parseArray(ruleStr);
				Iterator iter = rules.iterator();
				StringBuilder sb = new StringBuilder();
				while(iter.hasNext()) {
					Map rule = (Map)iter.next();
					sb.append("时间区间：").append(WeekEnum.getEnumByCode(Tool.toInt(rule.get("week_from"))).getDesc())
					.append("至").append(WeekEnum.getEnumByCode(Tool.toInt(rule.get("week_end"))).getDesc())
						.append("&nbsp;&nbsp;")
						.append(rule.get("time_from")+":00到").append(rule.get("time_end")+":00<br>")
						.append("价格：").append(RoomTypeEnum.getEnumByCode(Tool.toInt(rule.get("type"))).getDesc())
						.append("计费;").append(rule.get("price")+"元<br>");
				}*/
				room.put("rule_display", desc);
			}
		}
		
		Iterator iter = null;
		List teas = padDao.findPadItemsByOrderId(Maps.newHashMap("order_id", orderId, 
				"type", TeaTypeEnum.COMMON.getCode()));
		iter = teas.iterator();
		while(iter.hasNext()) {
			Map tea = (Map)iter.next();
			System.err.println("tea:"+tea);
			dealItem(tea);
		}
		List sampleteas = padDao.findPadItemsByOrderId(Maps.newHashMap("order_id", orderId, 
				"type", TeaTypeEnum.SAMPLE.getCode()));
		iter = sampleteas.iterator();
		while(iter.hasNext()) {
			Map sampletea = (Map)iter.next();
			System.err.println("sampletea:"+sampletea);
			dealItem(sampletea);
			
		}
		List desserts = padDao.findPadItemsByOrderId(Maps.newHashMap("order_id", orderId, 
				"type", TeaTypeEnum.DESSERT.getCode()));
		iter = desserts.iterator();
		while(iter.hasNext()) {
			Map dessert = (Map)iter.next();
			System.err.println("dessert:"+dessert);
			dealItem(dessert);
		}
		
		return new Maps().put("order", order).put("room", room).put("hall", hall).
				put("teas", teas).put("sampleteas", sampleteas).put("desserts", desserts).build();
	}
	
	private void dealItem(Map item) {
		item.put("unit_display", TeaUnitEnum.getEnumByCode(Tool.toInt(item.get("unit"))).getDesc());
		String otherStr = Tool.toString(item.get("other"));
		//System.err.println(otherStr);
		Map other = JSON.parseObject(otherStr);
		item.put("free", other==null?null:other.get("free"));
		item.put("weight", other==null?null:other.get("goods_weight"));
		String isFree = Tool.toString(item.get("free"));
		BigDecimal price = Tool.toBigDecimal(item.get("goods_price")).divide(new BigDecimal("100"));
		System.err.println(price);
		if("1".equals(isFree)) price = new BigDecimal("0");
		item.put("amount", price.multiply(Tool.toBigDecimal(item.get("goods_num"))));
		item.put("goods_price_display", price);
	}
	
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
	}

	@Transactional(readOnly=false, rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
	public void checkAndSaveOrder(Map map) {
		String cardNo = Tool.toString(map.get("vip_no"));
		String password = Tool.toString(map.get("vip_pwd"));
		if(StringUtils.isNotBlank(cardNo)) {
			Map account = customerDao.findVipAccount(Maps.newHashMap("cardno", cardNo, "password", password));
			if(account==null) throw new RuntimeException("会员卡密码错误！！");
		}
		
		int orderId = Tool.toInt(map.get("order_id"));
		Map order = padDao.findPadOrderById(orderId);
		int userId = Tool.toInt(order.get("user_id"));
		Map userStore = userDao.findStoreByUserId(userId);
		Map posOrder = new Maps(map).put("id", BusinessTool.generateId()).put("order_no", order.get("id"))
			.put("has_save", 0).put("user_id", order.get("user_id")).put("user_name", order.get("user_name"))
			.put("store_id", userStore.get("stid")).put("store_name", userStore.get("store_name"))
			.put("sum_amount", map.get("org_amount")).put("sum_buy", map.get("org_amount")).put("sum_save", 0)
			.put("pay_amount", map.get("now_amount")).put("type", TradeTypeEnum.PAD.getCode()).build();
		orderDao.saveOrder(posOrder);
		
		//处理库存
		List items = padDao.findPadOrderItemsByOrderId(Maps.newHashMap("id", orderId));
		Iterator iter = items.iterator();
		while(iter.hasNext()) {
			Map item = (Map)iter.next();
			
			//扣减仓库库存
			int unit = changeUnit(Tool.toInt(item.get("unit")));
			if(unit==4) continue;
			Map data = Maps.newHashMap(item.get("goods_id"), Maps.newHashMap("type", unit==2?1:0
			 , "unit", unit, "customerId", 0, "count", item.get("goods_num")));
			System.err.println(JSON.toJSONString(data));
			HttpRequest req = HttpRequest
	        .post(PropUtil.getValueByKey("url.stock"))
	        .form("storeId", userStore.get("stid"), "data", JSON.toJSONString(data));
			System.err.println(req.toString());
			HttpResponse response = req.send();
			System.err.println(response.body());
			Map result = JSON.parseObject(response.body());
			String msg = Tool.toString(result.get(item.get("goods_id")));
			if("error".equals(msg)) throw new RuntimeException("扣减库存失败！！");
		}
		padDao.updatePadOrderStatus(Maps.newHashMap("status", 2, "id", orderId));
	}
	
	public List getPadOrderItems(int orderId) {
		List items = padDao.findPadOrderItemsByOrderId(Maps.newHashMap("id", orderId, "type", 1));
		Iterator iter = items.iterator();
		while(iter.hasNext()) {
			Map item = (Map)iter.next();
			item.put("unit_display", TeaUnitEnum.getEnumByCode(Tool.toInt(item.get("myunit"))).getDesc());
			BigDecimal price = Tool.toBigDecimal(item.get("goods_price")).divide(new BigDecimal("100"));
			item.put("goods_price_display", price);
		}
		return items;
	}

	public Map checkAndSaveOrderItem(List products, int orderId) {
		boolean flag = false;String msg = null;
		List items = padDao.findPadOrderItemsByOrderId(Maps.newHashMap("id", orderId));
		Iterator iter = items.iterator();
		Map temp = Maps.newHashMap();
		while(iter.hasNext()) {
			Map item = (Map)iter.next();
			int cid = Tool.toInt(item.get("goods_id"));
			int num = Tool.toInt(item.get("goods_num"));
			int outNum = Tool.toInt(item.get("out_num"));
			temp.put(cid, num-outNum);
		}
		iter = products.iterator();
		Map count = Maps.newHashMap();
		int index = 0;
		while(iter.hasNext()) {
			Map product = (Map)iter.next();
			int pid = Tool.toInt(product.get("id"));
			//String code = Tool.toString(product.get("code"));
			if(count.get(pid)==null) {
				count.put(pid, 1);
			}
			int num = Tool.toInt(count.get(pid));
			int max = Tool.toInt(temp.get(pid));
			if(num+1>max) {
				msg = "发货列表中有商品数量超过客户购买数！！";
				break;
			}
			count.put(pid, num+1);
			if(!temp.containsKey(pid)) {
				msg = "发货列表中有用户没买的商品";
				break;
			}
			index++;;
		}
		if(index==products.size()) {
			Map order = orderDao.findOrderByNo(orderId+"");
			iter = products.iterator();
			while(iter.hasNext()) {
				Map product = (Map)iter.next();
				int unit = changeUnit(Tool.toInt(product.get("unit")));
				Maps.put(product, "id", BusinessTool.generateId(), "order_id", order.get("id")
						, "qrcode_id", product.get("code"), "is_save", 0, "product_name", product.get("name")
						,"now_price", product.get("price"), "org_price", 0, "discount", 0, "unit", unit, "order_no", orderId);
			}
			orderDao.saveOrderItems(products);
			
			Iterator<Map.Entry> entryIter = count.entrySet().iterator();
			while(entryIter.hasNext()) {
				Entry entry = entryIter.next();
				padDao.updateOutNum(Maps.newHashMap("order_id", orderId, "product_id", entry.getKey()
						, "num", entry.getValue()));
			}
			flag = true;
		}
		
		return Maps.newHashMap("isSuccess", flag, "msg", msg);
	}
	
	private int changeUnit(int unit) {
		int result = unit;
		switch(unit) {
		case 2:result = 0;break;
		case 3:result = 2;break;
		}
		return result;
	}
	
	/*private boolean getFlagByUnit(int unit) {
		return unit==1||unit==2;
	}*/

}
